package cn.yza.线程.异步;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

/**
 * @author Honglixi
 * @create 2021-11-06 14:57
 */
public class Test {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println("开始");
        CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                System.out.println("当前线程" + Thread.currentThread().getId());
                int i = 10 / 2;
                System.out.println("运行结果" + i);
            }
        },executor);
//        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//            System.out.println("当前线程" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果" + i);
//        }, executor);
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程" + Thread.currentThread().getId());
//            int i = 10 / 2;
//            System.out.println("运行结果" + i);
//            return i;
//        }, executor);
//        System.out.println(future.get()); //拿到结果
//        Thread.sleep(1);
//        System.out.println("结束");
        //测试完成后
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 0;
            System.out.println("运行结果" + i);
            return i;
        }, executor).whenComplete((res,excption) -> {
            //能得到异常信息，但是不能修改返回数据
            System.out.println("完成，结果是：" + res + "异常是："+ excption);
        }).exceptionally(new Function<Throwable, Integer>() {
            //可以感知异常，同时返回默认值
            @Override
            public Integer apply(Throwable throwable) {
                return 10;
            }
        });
        Integer integer = future.get();
        System.out.println("结果是" + integer);
//        /**
//         * 方法执行完成后的处理
//         */
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//        System.out.println("当前线程" + Thread.currentThread().getId());
//        int i = 10 / 0;
//        System.out.println("运行结果" + i);
//        return i;
//        }, executor).handle((res,throwable) -> {
//              if (res != null) {
//                  return res * 2;
//              }
//              if (throwable != null) {
//                  return 0;
//              }
//              return 0;
//        });
//        Integer integer = future.get();
//        System.out.println("返回结果" +integer);
    }
}
